package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    IWmSensitiveService sensitiveService;

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws Exception {
        EasyExcel.read(file.getInputStream(), WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            for (WmSensitive sensitive : dataList) {
                LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives, sensitive.getSensitives());
                int count = sensitiveService.count(queryWrapper);
                if (count == 0) {
                    sensitive.setCreatedTime(new Date());
                    sensitiveService.save(sensitive);
                }
            }
        })).sheet().doRead();
        return ResponseResult.okResult("导入成功");
    }
    @GetMapping("/excel/download")
    public ResponseResult download(HttpServletResponse response) throws Exception{
        List<WmSensitive> sensitiveList = sensitiveService.list();
        //        EasyExcel.write()
        response.addHeader("Content-Disposition", "attachment;filename=sensitive.xlsx");
        EasyExcel.write(response.getOutputStream(), WmSensitive.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return sensitiveList;
                });
        return ResponseResult.okResult();
    }
}
